/**
  * @description: 双表格（左/右）
  * @author: hj
  * @update: hj(2020-01-14)
  */

import React, {Component} from 'react';
// import {Table} from '@alifd/next';
import styles from './index.module.scss';
import {getMediaById} from '@/service/Api/Chart';
import { observer,inject,Provider } from 'mobx-react';

let tableTimer,tableTimer1,tableTimer2;

 
@inject('chartStore') 
@observer


class TableDouble extends Component {
    constructor(props) {
        super(props);
        this.state = {
            params: [],
            data: [],
            forceFit: true, //forceFit自动试用宽度，默认false
            width: this.props.data.width ? this.props.data.width : '100%',   // 固定宽度    当自适应宽度开启，此功能失效
            height: this.props.data.height ? this.props.data.height : '100%',
            condition: this.props.data.condition ? this.props.data.condition : '',
            pageFlag: this.props.data.pageFlag ? this.props.data.pageFlag : '',
            nofirst: this.props.data.nofirst ? this.props.data.nofirst : '',
            color: this.props.data.color,
            title: '',
            chartId: this.props.data.chartId,
            id: this.props.data.componentId,
            chartData: [],
            axisArr: {},
            columnMaps:[],
            haveData: false,
            groupTitle: [],

            dataNull: false, // 暂无数据

            // 全局变量
            mainData: [], // 操作组件可操作数据
            mainName: '', // 操作组件可操作当前维度
            mainFlag: false, // 是否是操作组件

            pageInitFlag: true,
            affectName: '',
            requireCondition: '',
        };
    };


    componentWillMount() { //初始化
        const _this = this;
        
        // 预览界面
        if (_this.state.pageFlag == 'preview') {
            // 判断当前组件是否是可操作组件
            const { globalData } = _this.props.chartStore;
            if (globalData.slice().length > 0) {
                globalData.slice().map((item,index) => {
                    if (item.affect == _this.state.chartId) { // 可操作组件
                        let affectName = item.affectDimension;
                        _this.setState({
                            mainFlag: true,
                            mainName: affectName
                        })
                    }
                })
            }

            _this.interfaceRequest(_this.state.chartId,_this.state.condition);
        } else { // 配置面板
            if (_this.state.nofirst == 'nofirst') {
                _this.saveHandleData();
            } else {
                _this.interfaceRequest(_this.state.chartId,_this.state.condition);
            }
        }
    }

    // 钩子函数--组件挂载完成后
    componentDidMount() { //初始化
        this.setState({
            haveData: true
        })
    }
    // 接收父组件的数据改变
    componentWillReceiveProps = (nextProps) => {
        const _this = this;
        const { globalData, affectId } = _this.props.chartStore;

        // 预览界面---判断是否是变化组件
        if (nextProps.data.pageFlag == 'preview') {
            if (nextProps.data.condition != _this.state.requireCondition && globalData.slice().length > 0) {
                globalData.slice().map((item,index) => {
                    if (item.affect == affectId && item.require == nextProps.data.chartId) { // 联动组件
                        _this.setState({
                            pageInitFlag: false
                        })
                        let condition = {};
                        Object.keys(_this.state.requireCondition).forEach(function(keys){
                            condition[keys] = keys == item.requireDimension ? nextProps.data.condition[keys] : _this.state.requireCondition[keys];
                        })
                        _this.interfaceRequest(nextProps.data.chartId,condition);
                    }
                })
            }
        }
    }

    // 数据接口请求
    interfaceRequest = (chartId,condition) => {
        this.setState({
            requireCondition: condition,
        });

        let data = {
            charId: chartId,
            condition: condition
        };
        this.getMediaById(data);
    }

    // 数据存储刷新
    saveHandleData = () => {
        const { chartArrData } = this.props.chartStore;
        if (chartArrData.slice().length > 0) {
            chartArrData.slice().map((item) => {
                if (item.id == this.state.chartId) {
                    this.setState({
                        haveData: false
                    },function() {
                        // 数据处理
                        this.handleData(item);
                    })
                }
            })
        }
    }


    async getMediaById(data) {
        const res = await getMediaById(data);
        if (res.data && res.data.code === 0) {
            let str = res.data;
            if (str.data && str.data.data && str.data.data.length > 0) {
                // 存储图例原始数据
                const { saveChartData } = this.props.chartStore;
                let oldData = {
                    id: this.state.chartId,
                    data: str.data.data
                }
                saveChartData(oldData);

                // 数据处理
                this.handleData(str.data);
            } else {
                this.setState({
                    dataNull: []
                })
            }
        } else {
            this.setState({
                dataNull: []
            })
        }
    }
    // 数据处理
    handleData = (allData) => {
        let storeAllData = allData.data.slice();
        this.setState({
            dataNull: []
        })

        // 非预览界面
        if (this.state.pageFlag != 'preview') {
            // 存储可操作组件数据
            if (allData.affect && allData.affect.length > 0) {
                let obj = {
                    id: this.state.chartId,
                    label: allData.doubleChartTitle ? allData.doubleChartTitle : '',
                    dimensionData: []
                }
                const { saveAffectData } = this.props.chartStore;

                let dimensionData = [];
                allData.affect.slice().map((item,index) => {
                    dimensionData.push(item);
                })
                obj.dimensionData = dimensionData;
                saveAffectData(obj);
            }
            // 存储联动组件数据
            if (allData.requires && allData.requires.length > 0) {
                let obj = {
                    id: this.state.chartId,
                    label: allData.doubleChartTitle ? allData.doubleChartTitle : '',
                    dimensionData: []
                }
                const { saveRequireData } = this.props.chartStore;

                let dimensionData = [];
                allData.requires.slice().map((item,index) => {
                    dimensionData.push(item);
                })
                obj.dimensionData = dimensionData;
                saveRequireData(obj);
            }
        }

        // 页面初始化
        if (this.state.pageInitFlag) {
            if (allData.affect &&  allData.affect.length > 0) {
                this.setState({
                    affectName: allData.affect[0]
                });
            }
            // 获取选择项
            if (allData.conditionValues) {
                let selectData = allData.conditionValues[allData.affect[0]] ? allData.conditionValues[allData.affect[0]] : [];
                this.setState({
                    mainData: selectData
                });
            }
        }
        let groupTitle = [];
        let tableData = [];
        storeAllData.map((item,index) => {
            let data = this.groupData(item);
            tableData.push(data);
            groupTitle.push(item.title);
        })

        this.setState({
            chartData: tableData,
            groupTitle: groupTitle
        })

    }
    // 分组数据处理
    groupData = (storeData) => {
        const _this = this;

        let newData = {
            title: '',
            chartData: []
        }

        // 组装当前图例的维度和度量
        let xyArr = storeData.columns ? storeData.columns.split(',') : [];

        // 表头
        let colnums = [];
        let noName = '';
        if (xyArr.length > 0) {
            xyArr.map((v,i) => {
                let obj = {};
                Object.keys(storeData.columnMaps).forEach(function(key){
                    if (key == v) {
                        obj = {
                            "key": v,
                            "value": storeData.columnMaps[v]
                        }
                    }
                })
                colnums.push(obj);
            })
        }

        // 表数据
        let colnumsData = [];
        storeData.data.map((item,index) => {
            let objData = [];
            xyArr.map((v,i) => {
                if (v != noName) {
                    objData.push({
                        "key": v,
                        "value": item[v]
                    })
                }
            })
            colnumsData.push(objData);
        })

        newData = {
            title: storeData.title,
            colnums: colnums,
            colnumsData: colnumsData
        };
        return newData;
    }

    // 改变全局变量
    onGlobalVariable = (val) => {
        this.props.onGlobalVariable(val);
    }

    // table无缝隙循环滚动
    Marquee = (index) => {
        let speed = 200;
        let table = document.getElementById(this.state.id+'_'+this.state.chartId+'_'+index+'_table');
        let table1 = document.getElementById(this.state.id+'_'+this.state.chartId+'_'+index+'_table1');
        let table2 = document.getElementById(this.state.id+'_'+this.state.chartId+'_'+index+'_table2');
        table2.innerHTML = table1.innerHTML != null ? table1.innerHTML : '';

        if (index == 0) {
            if (tableTimer1) window.clearInterval(tableTimer1);
            tableTimer1 = window.setInterval(() => {
                if (table2.offsetTop - table.scrollTop <= 0) {
                    table.scrollTop -= table1.offsetHeight;
                } else {
                    table.scrollTop++;
                }
            },speed)
        } else {
            if (tableTimer2) window.clearInterval(tableTimer2);
            tableTimer2 = window.setInterval(() => {
                if (table2.offsetTop - table.scrollTop <= 0) {
                    table.scrollTop -= table1.offsetHeight;
                } else {
                    table.scrollTop++;
                }
            },speed)
        }
    } 
    

    render() {
        let Layer = this.props.layer;

        if (this.state.pageFlag == 'preview') {
            setTimeout(() => {
                if (this.state.chartData.length > 0) {
                    let index = 0;
                    if (this.state.chartData[index].colnumsData.length > 0) {
                        this.Marquee(index);
                    }

                    setTimeout(() => {
                        index++;
                        if (this.state.chartData[index].colnumsData.length > 0) {
                            this.Marquee(index);
                        }
                    },500);
                }
            },2000);
        }
        

        return (
            
            <div id={this.state.id+'_'+this.state.chartId} style={{zIndex: 99,width: this.state.width,height: this.state.height,padding: '70px 2% 30px 2%'}}>
                <Layer width={this.state.width} title={this.state.title} groupTitle={this.state.groupTitle} chartId={this.state.chartId} choiceData={this.state.mainData} onGlobalVariable={this.onGlobalVariable}></Layer>
                
                <div id={'chart_'+this.state.id+'_'+this.state.chartId} style={{height: this.state.height - 100}}>
                    {this.state.chartData.length > 0 && this.state.chartData.map((itemData,indexData) => {
                        if (itemData.colnumsData.length > 0) {
                            let maxH = 0;
                            if ((itemData.colnumsData.length + 1) * 30 < (this.state.height * - 100)) {
                                maxH = (itemData.colnumsData.length + 1) * 30
                            } else {
                                maxH = Math.ceil((this.state.height * 0.8) / 30) * 30;
                            }

                            let tdWidth = Math.floor(100 / itemData.colnums.length) + '%';
                            return (
                                <div id={'chart_'+this.state.id+'_'+this.state.chartId+'_'+indexData} style={{display: 'inline-block',float: indexData == 0 ? 'left' : 'right',width: '48%',height: '100%',overflow: 'hidden'}}>
                                    <div style={{height: '30px'}}>
                                        <table className={styles.tableBox} cellpadding="0" cellspacing="0">
                                            <tr>
                                                {itemData.colnums.length>0 && itemData.colnums.map((item,index) => {
                                                    return (
                                                        <th title={item.value} style={{color: '#24C6F5',width: tdWidth}}> {item.value} </th>
                                                    )
                                                })}
                                            </tr>
                                        </table>
                                    </div>
                                    <div id={this.state.id+'_'+this.state.chartId+'_'+indexData+"_table"} style={{overflow: 'hidden',height: maxH-30+ 'px'}}>
                                        <div id={this.state.id+'_'+this.state.chartId+'_'+indexData+"_table1"}>
                                            <table className={styles.tableBox} cellpadding="0" cellspacing="0">
                                                {itemData.colnumsData.length > 0 && itemData.colnumsData.map((item,index) => {
                                                    return (
                                                        <tr>
                                                            {item.map((v,i) => {
                                                                return (
                                                                    <td title={v.value} style={{color: '#72F1F8',padding: 0,margin: 0,width: tdWidth}}> {v.value} </td>
                                                                )
                                                                
                                                            })}
                                                        </tr>
                                                    )
                                                })}
                                            </table>
                                        </div>
                                        <div id={this.state.id+'_'+this.state.chartId+'_'+indexData+"_table2"}></div>
                                    </div>
                                </div>
                            )
                        } else {
                            return (
                                <p style={{height: this.state.height - 100,lineHeight: this.state.height - 100 + 'px',color: '#fff',textAlign: 'center'}}> 暂无数据 </p>
                            )
                        }
                    })}
                </div>
                
            </div>
        );
    }


}

export default TableDouble;

